<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>同页面直播+观看演示</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        margin: 20px;
      }
      .container {
        display: flex;
        gap: 20px;
      }
      .panel {
        border: 1px solid #ddd;
        padding: 20px;
        border-radius: 8px;
        flex: 1;
      }
      video {
        width: 100%;
        height: 200px;
        border: 2px solid #ccc;
        margin: 10px 0;
      }
      button {
        padding: 10px 20px;
        margin: 5px;
      }
      .log {
        background: #f5f5f5;
        padding: 10px;
        height: 150px;
        overflow-y: auto;
        font-family: monospace;
        font-size: 12px;
      }
    </style>
  </head>
  <body>
    <h1>同页面直播+观看演示</h1>

    <div class="container">
      <div class="panel">
        <h3>主播端</h3>
        <video id="localVideo" autoplay muted playsinline></video>
        <button id="startBtn">开始直播</button>
        <button id="stopBtn" disabled>停止直播</button>
        <div>直播间ID: <span id="streamId">-</span></div>
      </div>

      <div class="panel">
        <h3>观众端</h3>
        <video id="remoteVideo" autoplay playsinline controls></video>
        <input type="text" id="roomInput" placeholder="输入直播间ID" />
        <button id="joinBtn">加入观看</button>
        <button id="leaveBtn" disabled>离开</button>
      </div>
    </div>

    <div class="panel">
      <h3>调试日志</h3>
      <div id="log" class="log"></div>
      <button onclick="clearLog()">清空日志</button>
    </div>

    <script>
      // 关键：创建两个独立的WebRTC管理器
      class WebRTCManager {
        constructor(name) {
          this.name = name;
          this.socket = null;
          this.peerConnection = null;
          this.isConnected = false;
          this.streamId = null;

          this.config = {
            iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
          };
        }

        async connect() {
          return new Promise((resolve, reject) => {
            this.socket = new WebSocket("ws://localhost:3003");

            this.socket.onopen = () => {
              log(`${this.name}: WebSocket连接成功`);
              this.isConnected = true;
              resolve();
            };

            this.socket.onmessage = (event) => {
              const message = JSON.parse(event.data);
              this.handleMessage(message);
            };

            this.socket.onerror = (error) => {
              log(`${this.name}: WebSocket错误: ${error}`);
              reject(error);
            };
          });
        }

        async handleMessage(message) {
          log(`${this.name}: 收到消息 ${message.type}`);
          // 这里可以复用之前的消息处理逻辑
          // 为了演示，简化处理
        }

        sendMessage(message) {
          if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(message));
          }
        }

        async startStreaming(stream) {
          this.peerConnection = new RTCPeerConnection(this.config);

          stream.getTracks().forEach((track) => {
            this.peerConnection.addTrack(track, stream);
          });

          const streamId = "stream_" + Math.random().toString(36).substr(2, 9);
          this.streamId = streamId;

          this.sendMessage({
            type: "start-stream",
            streamId: streamId,
          });

          log(`${this.name}: 开始直播 ${streamId}`);

          // 回调通知直播间ID已生成
          if (this.onStreamStarted) {
            console.log("调用onStreamStarted回调, streamId:", streamId);
            this.onStreamStarted(streamId);
          } else {
            console.warn("⚠️ onStreamStarted回调未设置!");
          }

          return streamId;
        }

        async joinStream(streamId) {
          this.peerConnection = new RTCPeerConnection(this.config);

          this.peerConnection.ontrack = (event) => {
            log(`${this.name}: 收到远程流`);
            const remoteVideo = document.getElementById("remoteVideo");
            remoteVideo.srcObject = event.streams[0];
            remoteVideo.play().catch((e) => log(`播放错误: ${e.message}`));
          };

          this.sendMessage({
            type: "join-stream",
            streamId: streamId,
          });

          log(`${this.name}: 加入直播间 ${streamId}`);
        }
      }

      // 创建两个独立的WebRTC实例
      const broadcasterRTC = new WebRTCManager("主播");
      const viewerRTC = new WebRTCManager("观众");

      const localVideo = document.getElementById("localVideo");
      const remoteVideo = document.getElementById("remoteVideo");
      const startBtn = document.getElementById("startBtn");
      const stopBtn = document.getElementById("stopBtn");
      const joinBtn = document.getElementById("joinBtn");
      const leaveBtn = document.getElementById("leaveBtn");
      const streamIdSpan = document.getElementById("streamId");
      const roomInput = document.getElementById("roomInput");
      const logDiv = document.getElementById("log");

      function log(message) {
        console.log(message);
        const time = new Date().toLocaleTimeString();
        logDiv.innerHTML += `[${time}] ${message}\n`;
        logDiv.scrollTop = logDiv.scrollHeight;
      }

      function clearLog() {
        logDiv.innerHTML = "";
      }

      startBtn.addEventListener("click", async () => {
        try {
          log("📹 获取摄像头权限...");
          const stream = await navigator.mediaDevices.getUserMedia({
            video: { width: 640, height: 480 },
            audio: true,
          });
          localVideo.srcObject = stream;

          // 设置直播间ID显示回调
          broadcasterRTC.onStreamStarted = (streamId) => {
            log(`📋 直播间ID已生成: ${streamId}`);
            console.log("设置直播间ID到页面:", streamId);
            streamIdSpan.textContent = streamId;
            roomInput.value = streamId; // 自动填入房间ID
            console.log("页面显示元素值:", streamIdSpan.textContent);
          };

          log("🔗 主播端连接WebSocket...");
          await broadcasterRTC.connect();

          const streamId = await broadcasterRTC.startStreaming(stream);

          startBtn.disabled = true;
          stopBtn.disabled = false;

          log(`🎬 直播开始! 房间ID: ${streamId}`);
        } catch (error) {
          log(`❌ 开始直播失败: ${error.message}`);
        }
      });

      stopBtn.addEventListener("click", async () => {
        try {
          // 停止摄像头
          const stream = localVideo.srcObject;
          if (stream) {
            stream.getTracks().forEach((track) => track.stop());
            localVideo.srcObject = null;
          }

          // 关闭PeerConnection
          if (broadcasterRTC.peerConnection) {
            broadcasterRTC.peerConnection.close();
            broadcasterRTC.peerConnection = null;
          }

          // 关闭WebSocket连接
          if (broadcasterRTC.socket) {
            broadcasterRTC.socket.close();
            broadcasterRTC.isConnected = false;
          }

          // 清空UI
          streamIdSpan.textContent = "-";
          roomInput.value = "";
          startBtn.disabled = false;
          stopBtn.disabled = true;

          log("🛑 直播已停止");
        } catch (error) {
          log(`❌ 停止直播失败: ${error.message}`);
        }
      });

      joinBtn.addEventListener("click", async () => {
        try {
          const streamId = roomInput.value.trim();
          if (!streamId) {
            log("❌ 请输入直播间ID");
            return;
          }

          log("🔗 观众端连接WebSocket...");
          await viewerRTC.connect();

          await viewerRTC.joinStream(streamId);

          joinBtn.disabled = true;
          leaveBtn.disabled = false;

          log(`👀 加入观看: ${streamId}`);
        } catch (error) {
          log(`❌ 加入观看失败: ${error.message}`);
        }
      });

      leaveBtn.addEventListener("click", async () => {
        try {
          // 停止远程视频
          remoteVideo.srcObject = null;

          // 关闭PeerConnection
          if (viewerRTC.peerConnection) {
            viewerRTC.peerConnection.close();
            viewerRTC.peerConnection = null;
          }

          // 关闭WebSocket连接
          if (viewerRTC.socket) {
            viewerRTC.socket.close();
            viewerRTC.isConnected = false;
          }

          // 重置UI
          joinBtn.disabled = false;
          leaveBtn.disabled = true;

          log("👋 已离开观看");
        } catch (error) {
          log(`❌ 离开观看失败: ${error.message}`);
        }
      });

      log("🚀 同页面直播+观看演示已就绪");
      log("💡 原理：使用两个独立的WebSocket连接模拟不同客户端");
      log("📋 测试步骤: 1.点击开始直播 2.点击加入观看");
    </script>
  </body>
</html>
